<template>
  <!-- 区总 -->
  <!-- 主播管理 -->
  <a-spin class="anchor-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter new-filter">
      <div class="l search-box-item">
        <div>
          <span class="label-text-small">站点：</span>
          <a-select
            showSearch
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="getAllStation($event)"
            @change="changeLocation"
            v-model="search.localtionId"
            placeholder="请选择站点"
            class="search-width-small"
          >
            <a-select-option :value="null">全部</a-select-option>
            <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>

        <div>
          <span class="label-text-small">产品名称/ID：</span>
          <a-input-search class="search-width-small" type="text" placeholder="产品名称/产品ID" allowClear v-model="search.keyWord" @search="handleByQueryCond" />
        </div>
        <div>
          <span class="label-text-small">SPU提审状态：</span>
          <a-select class="search-width-small" placeholder="请选择SPU提审状态" v-model="search.spuStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in spuStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span class="label-text-small">POI通过状态：</span>
          <a-select class="search-width-small" placeholder="请选择状态" v-model="search.materialStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in qualificationReviewStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span class="label-text-middle">食客玩家上线状态：</span>
          <a-select class="search-width-small" placeholder="请选择状态" v-model="search.dyStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in programStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span class="label-text-small">商品上线：</span>
          <a-range-picker class="search-width-middle" @change="handleByQueryCond" v-model="search.selectDateGood" />
        </div>
        <div>
          <span class="label-text-middle">SPU状态修改：</span>
          <a-range-picker class="search-width-middle" @change="handleByQueryCond" v-model="search.selectDate" />
        </div>
      </div>

      <div class="search-new-r">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body self-time-line">
      <a-table :columns="tableColumns" :pagination="false" :data-source="spuList" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <!-- 产品相关 -->
        <template slot="productId" slot-scope="text, record">
          <div class="product-item-box">
            <div>
              <p><span class="font-weight-bold">产品ID：</span>{{ record.productId || '无' }}</p>
              <p><span class="font-weight-bold">产品名称：</span>{{ record.productName || '无' }}</p>
              <p><span class="font-weight-bold">产品品类：</span>{{ record.productType || '无' }}</p>
              <p><span class="font-weight-bold">套餐ID：</span>{{ record.productItemId || '无' }}</p>
              <p><span class="font-weight-bold">套餐名称：</span>{{ record.productItemName || '无' }}</p>
              <p><span class="font-weight-bold">抖音映射ID：</span>{{ record.mdyId || '无' }}</p>
              <p><span class="font-weight-bold">SPU_ID：</span>{{ record.spuId || '无' }}</p>
            </div>
            <div>
              <p><span class="font-weight-bold">站点：</span>{{ record.city || '无' }}</p>
              <p><span class="font-weight-bold">产品经理：</span>{{ record.pmName || '无' }}</p>
              <p><span class="font-weight-bold">合同名称：</span>{{ record.contactName || '无' }}</p>
              <p><span class="font-weight-bold">售价/原价：</span>{{ record.salePriceYuan || 0 }}/{{ record.originPriceYuan || 0 }}</p>
              <p><span class="font-weight-bold">剩余库存：</span>{{ record.stockAmount || 0 }}</p>
              <p><span class="font-weight-bold">合作主播数：</span>{{ record.dyUserNum || 0 }}</p>
              <p><span class="font-weight-bold">主播请款金额：</span>{{ record.dyUserMoneyYuan || 0 }}</p>
            </div>
          </div>
        </template>
        <!-- 订单量 -->
        <template slot="productItemSales" slot-scope="text, record">
          <p><span class="font-weight-bold">销量：</span>{{ record.productItemSales || 0 }}</p>
          <p><span class="font-weight-bold">核销量：</span>{{ record.productItemCompleteSales || 0 }}</p>
          <p><span class="font-weight-bold">退款量：</span>{{ record.productItemRefundSales || 0 }}</p>
          <p>
            <span class="font-weight-bold">
              已核销CPS佣金
              <a-tooltip placement="right" overlayClassName="time-line-tooltip">
                <template slot="title">
                  已核销3天后到账的CPS佣金金额(不包含核销未满3天的金额)
                </template>
                <a-icon type="question-circle" :style="{ fontSize: '13px', color: '#4E5969' }" />
              </a-tooltip>
              ：
            </span>
            {{ record.productItemCps || 0 }}
          </p>
          <p>
            <span class="font-weight-bold">
              CPS佣金
              <a-tooltip placement="right" overlayClassName="time-line-tooltip">
                <template slot="title">
                  已在抖音平台生效的CPS佣金
                </template>
                <a-icon type="question-circle" :style="{ fontSize: '13px', color: '#4E5969' }" />
              </a-tooltip>
              ：
            </span>
            {{ record.cpsAmount ? record.cpsAmount + '元' : '0元' }}
          </p>
          <p><span class="font-weight-bold">佣金：</span>{{ record.byteDanceMoney || '无' }}</p>
        </template>
        <!-- 套餐状态 -->
        <template slot="statusFlowList" slot-scope="text, record">
          <a-timeline>
            <a-timeline-item :color="item.lightFlag ? '#57AE59' : 'rgb(206, 205, 205)'" :class="[item.lightFlag ? '' : 'no-line']" v-for="item in record.statusFlowList" :key="item.sort">
              <div class="min-hei-auto">
                <div class="flex-title">
                  <p class="title-text">
                    {{ item.title || 'Title' }}
                    <a-tooltip placement="right" overlayClassName="time-line-tooltip" v-if="item.sort === 2">
                      <template slot="title">
                        <span>{{ item.remark || '' }}</span>
                      </template>
                      <a-icon type="question-circle" :style="{ fontSize: '13px', color: '#4E5969' }" />
                    </a-tooltip>
                  </p>
                  <div :class="['tag-box', item.color === 1 ? 'tag-box-gray' : item.color === 2 ? 'tag-box-green' : 'tag-box-red']">{{ item.statusDesc }}</div>
                </div>
                <p class="time-text">{{ item.time || '' }}</p>
                <a-tooltip placement="right" overlayClassName="time-line-tooltip" v-if="item.sort !== 1 && item.reason && item.reason.length === 1 && item.reason[0].length > 12">
                  <template slot="title">
                    <div>1、{{ item.reason[0] }}</div>
                  </template>
                  <div class="reason-text">1、{{ item.reason[0] }}</div>
                </a-tooltip>
                <div class="reason-text" v-else-if="item.sort !== 1 && item.reason && item.reason.length === 1">1、{{ item.reason[0] }}</div>
                <a-tooltip placement="right" overlayClassName="time-line-tooltip" v-else-if="item.sort !== 1 && item.reason && item.reason.length > 1">
                  <template slot="title">
                    <div v-for="(v, index) in item.reason" :key="v">{{ index + 1 }}、{{ v }}</div>
                  </template>
                  <div class="reason-text" v-for="(v, index) in item.reason.slice(0, 1)" :key="v">{{ index + 1 }}、{{ v }}</div>
                  <div class="shou-more">显示更多>></div>
                </a-tooltip>
              </div>
            </a-timeline-item>
          </a-timeline>
        </template>
        <!-- 时间 -->
        <template slot="expirTime" slot-scope="text, record">
          <p><span class="font-weight-bold">BD上线时间：</span>{{ record.releaseTime || '无' }}</p>
          <p><span class="font-weight-bold">产品过期时间：</span>{{ record.validEndDate || '无' }}</p>
          <p><span class="font-weight-bold">SPU提审时间：</span>{{ record.applyTime || '无' }}</p>
          <p><span class="font-weight-bold">SPU审核时间：</span>{{ record.auditTime || '无' }}</p>
          <p><span class="font-weight-bold">抖音团购过期时间：</span>{{ record.expirTime || '无' }}</p>
        </template>
        <!-- 商家资质 -->
        <template slot="urls" slot-scope="text, record">
          <div style="display:flex" v-for="(item, index) in record.qualification" :key="index">
            <p v-for="(v, i) in urlName" :key="i" v-show="index === v.value" style="width:80px;text-align:right;">{{ v.name }} :&nbsp;</p>
            <div v-if="item && item.length > 0">
              <upload v-show="item && item.length > 0" :limit="item.length" disabled :value="item"> </upload>
            </div>
            <div v-else style="margin:0 0 3px 0;">无</div>
          </div>
        </template>
        <!-- 操作按钮 -->
        <template slot="action" slot-scope="text, record">
          <a-button type="link" href="javascript:;" size="small" @click="toSpuManag(record.mdyId)">POI管理</a-button>
          <!-- 对SPU状态为“审核中”的产品提供按钮，刷新SPU状态 -->
          <a-button
            type="link"
            href="javascript:;"
            v-if="record.spuStatus === 0 || record.spuStatus === 1 || record.spuStatus === 2 || record.spuStatus === 3"
            size="small"
            @click="spuRefrsh(record.mdyId)"
            >更新状态</a-button
          >
          <a-button type="link" href="javascript:;" size="small" @click="handleOpenUpGoods(record.mdyId)">上架抖音</a-button>
          <a-button type="link" href="javascript:;" size="small" @click="handleOpenoffGoods(record.mdyId)">下架抖音</a-button>
          <!-- 资质审核状态存在：待提审、审核拒绝，显示该按钮 -->
          <div v-if="record.materialStatusStr.search('审核拒绝') != -1 || record.materialStatusStr.search('待提审') != -1">
            <a-tooltip placement="bottom">
              <template slot="title">
                只会对待提审、审核拒绝的商家资质发起提审
              </template>
              <a-button type="link" href="javascript:;" size="small" @click="syncSJZZ(record.mdyId)">提交商家资质审核</a-button>
            </a-tooltip>
          </div>
          <!-- 资质审核状态有且唯一是“审核通过”、小程序状态-在线未售罄 激活 -->
          <div v-if="record.dyStatus === 1 && record.materialStatusStr === '审核通过'">
            <a-tooltip placement="bottom">
              <template slot="title">
                若该产品之前已在抖音上架，重新同步审核若不通过会将SPU在抖音侧的上架状态变为不通过
              </template>
              <a-button type="link" href="javascript:;" size="small" @click="syncSpu(record.mdyId, record.spuStatus)">提交SPU审核</a-button>
            </a-tooltip>
          </div>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="search.pageSize"
        v-model="search.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
  </a-spin>
</template>

<script>
import { spuListUrlElse, poiSpuRefreshUrl, poiSpuSyncUrl, pointLocationList, offGoodsMessage, offGoods, syncMerchantQualificationReview, getH5url } from '@/service'
import upload from '@/components/upload/upload'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { columnsConfig } from '../columns'
export default {
  name: 'spuList',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      moment,
      // loading是否显示
      isLoading: false,
      urlName: [
        { name: '营业执照', value: 'bizLicencePath' },
        { name: '商家授权函', value: 'contractPath' },
        { name: '行业许可证', value: 'qualMaterial' },
        { name: '商家证明', value: 'merchantCertificate' },
        { name: '其他资质', value: 'additionalQual' }
      ],
      pagination: {
        total: 0
      },
      // 全部站点
      allStation: [],
      // table数据查询条件
      search: {
        keyWord: '',
        selectDate: [],
        selectDateGood: [],
        shopId: '',
        spuStatus: '',
        dyStatus: '',
        localtionId: '',
        materialStatus: '',
        pageIndex: 1,
        pageSize: 10
      },

      // 订单列表
      spuList: [],
      // 主播列表总数据条数
      anchorTotal: 0,
      tableColumns: columnsConfig.spuColumns
    }
  },

  components: {
    upload
  },

  computed: {
    // SPU状态
    spuStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '未提审',
          value: -1
        },
        {
          name: '审核中',
          value: 0
        },
        {
          name: '上架',
          value: 1
        },
        {
          name: '下架',
          value: 2
        },
        {
          name: '抖音审核拒绝',
          value: 3
        }
      ]
    },
    programStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '在线',
          value: 1
        },
        {
          name: '下线',
          value: 2
        }
      ]
    },
    qualificationReviewStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '审核中',
          value: 0
        },
        {
          name: '审核通过',
          value: 1
        },
        {
          name: '审核拒绝',
          value: 2
        },
        {
          name: '待提审',
          value: 3
        },
        {
          name: '无资质',
          value: 4
        },
        {
          name: '协议已过期',
          value: 5
        }
      ]
    }
  },

  methods: {
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.search.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.search.pageIndex = num
      this.setPath(this.getParams())
      this.query()
    },
    getAllStation(e) {
      pointLocationList({ city: e }).then((res) => {
        console.log(res)
        this.allStation = res
      })
    },
    handleZtDisSolution() {
      this.ztDisVisible = false
    },
    // 拿参数
    getParams() {
      // const { pageIndex, pageSize } = this.pagination
      const { keyWord, shopId, spuStatus, dyStatus, selectDate = [], localtionId, materialStatus, selectDateGood = [], pageIndex, pageSize } = this.search

      return {
        pageIndex,
        pageSize,
        dyStatus,
        spuStatus,
        materialStatus,
        shopId,
        keyWord,
        localtionId,
        startTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined,
        releaseStartTime: selectDateGood[0] ? moment(selectDateGood[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        releaseEndTime: selectDateGood[1] ? moment(selectDateGood[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },

    // 初始化
    initQuery() {
      // this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, keyWord, shopId, startTime, endTime, spuStatus, dyStatus, materialStatus, releaseStartTime, releaseEndTime, localtionId } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          pageIndex: isNaN(pageIndex) ? 1 : +pageIndex,
          pageSize: 10,
          localtionId: isNaN(localtionId) ? null : +localtionId,
          shopId: shopId || '',
          keyWord: keyWord || '',
          spuStatus: isNaN(spuStatus) ? '' : spuStatus === 0 ? '0' : +spuStatus,
          materialStatus: isNaN(materialStatus) ? '' : materialStatus === 0 ? '0' : +materialStatus,
          dyStatus: +dyStatus || '',
          selectDate: startTime && endTime ? [startTime, endTime] : [],
          selectDateGood: releaseStartTime && releaseEndTime ? [releaseStartTime, releaseEndTime] : []
        }
      }
    },
    // 选择了站点
    changeLocation() {
      this.search.pageIndex = 1
      this.initQuery()
    },

    /**
     * 获取主播信息列表
     * 具体参数参考 getAnchorInfoListApi 方法
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      spuListUrlElse(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.spuList = Object.freeze(rs.spuListData) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key] || origin[key] === 0) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    toSpuManag(id = '') {
      // 产品ID
      this.$router.push({
        path: '/spuManag',
        query: {
          id,
          idJudge: 1
        }
      })
    },
    spuRefrsh(mdyId = '') {
      this.isLoading = true
      poiSpuRefreshUrl({ productId: mdyId })
        .then(() => {
          this.query()
        })
        .finally(() => {
          this.isLoading = false
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    // 同步spu
    syncSpu(id = '', spuStatus = '') {
      if (spuStatus === 0) {
        this.$confirm({
          title: '同步SPU',
          content: '产品已在抖音审批队列中，是否继续重新申请同步？',
          okText: '确定',
          okType: 'primary',
          onOk: () => {
            // 发送请求
            return poiSpuSyncUrl({ productId: id })
              .then((rs) => {
                this.$messageSend.success('操作成功')
                this.query()
              })
              .catch((err) => err)
          },
          onCancel() {}
        })
      } else {
        // 请求接口
        this.isLoading = true
        poiSpuSyncUrl({ productId: id })
          .then(() => {
            this.query()
          })
          .finally(() => {
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })
      }
    },
    // 提交商家资质审核
    syncSJZZ(id) {
      const _this = this
      this.$confirm({
        title: '提交商家资质审核',
        content: '你确定要提交商家资质审核吗？',
        okText: '确定',
        okType: 'primary',
        onOk: () => {
          // 发送请求
          return syncMerchantQualificationReview({ productId: id })
            .then((rs) => {
              _this.$confirm({
                content: rs,
                onOk() {
                  _this.query()
                },
                onCancel() {}
              })
            })
            .catch((err) => err)
        },
        onCancel() {}
      })
    },
    // 打开下架确认框
    handleOpenoffGoods(id) {
      const _this = this
      // 打开弹窗信息回填
      offGoodsMessage({ productId: id }).then((msg) => {
        this.$confirm({
          content: msg,
          onOk() {
            // 发送确认下架请求并刷新
            return offGoods({ byteVisible: 0, bizProductId: id })
              .then(() => {
                _this.$messageSend.success('操作成功')
                _this.query()
              })
              .catch((err) => err)
          },
          onCancel() {}
        })
      })
    },
    // 打开上架确认框
    handleOpenUpGoods(id) {
      const _this = this
      this.$confirm({
        content: '确定上架抖音吗？',
        onOk() {
          // 发送确认上架架请求并刷新
          return offGoods({ byteVisible: 1, bizProductId: id })
            .then(() => {
              _this.$messageSend.success('操作成功')
              _this.query()
            })
            .catch((err) => err)
        },
        onCancel() {}
      })
    },
    handleMultiStoreQualificationFilling(productId) {
      getH5url({ productId: productId })
        .then((res) => {
          this.$confirm({
            title: `链接：${res}`,
            content: '请将此链接发给相关人员，按商家地址上传商家资质'
          })
        })
        .catch((err) => err)
    }
  },

  async mounted() {
    // 获取所有站点
    pointLocationList({ city: '' })
      .then((res = []) => {
        this.setSearch()
        this.allStation = res
        this.query()
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)
  },

  filters: {
    // 获取直播平台
    getPlatform(val) {
      if (!val) return '无'
      return val === 1 ? '抖音' : '快手'
    }
  }
}
</script>

<style lang="less" scoped>
.anchor-review {
  padding: 16px;
}
/deep/ .ant-upload-list-picture-card .ant-upload-list-item,
/deep/ .ant-upload-list-picture-card-container {
  width: 30px;
  height: 30px;
  margin: -6px 3px 6px 0;
  padding: 3px;
  border-radius: 2px;
}
table tbody td div {
  margin-top: 2px;
}
/deep/ table tbody td a {
  margin-right: 0;
}
.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.multi-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; // 超出两行则以...形式隐藏
  -webkit-box-orient: vertical;
}
.ztDis_box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-top: 0 !important;
}
.zt_discrible_btn {
  color: #0090ff;
  cursor: pointer;
  position: relative;
  top: 6px;
  left: 3px;
}

.zt_discrible_solution_list {
  list-style: none;
}
p {
  margin-bottom: 5px;
  font-size: 13px;
}
.font-weight-bold {
  font-weight: bold;
  display: inline-block;
}
</style>
